import { useWebSocket } from '@vueuse/core'
import { ref, watchEffect } from 'vue'

import { useUserStore } from '@/store'

interface IData {
  event: string
  data: Record<string, any>
}

export function useWs() {
  const dataProxy = ref<IData>({})

  const { token } = useUserStore()
  const { status, data, send, open, close } = useWebSocket(
    import.meta.env.VITE_APP_WS
  )

  function sendProxy(event: string, data: Record<string, any> = {}) {
    send(
      JSON.stringify({
        event,
        data: {
          headers: {
            authorization: `Bearer ${token}`
          },
          body: data
        }
      })
    )
  }

  watchEffect(() => {
    dataProxy.value = JSON.parse(data.value)
  })

  return {
    dataProxy,
    sendProxy
  }
}
